package com.jinlejia.erp.ui.new_house.apply;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.PhotoAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.SaveCookieBean;
import com.jinlejia.erp.common.WrapContentLinearLayoutManager;
import com.jinlejia.erp.databinding.ActivityVisitApplyBinding;
import com.jinlejia.erp.ui.common.ImageViewPagerActivity;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.utils.ACache;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DateUtil;
import com.jinlejia.erp.utils.DbUtil;
import com.jinlejia.erp.utils.RxUpLoad;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.nereo.multi_image_selector.MultiImageSelector;
import okhttp3.Call;
import okhttp3.MediaType;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import top.zibin.luban.Luban;

import static top.zibin.luban.Luban.THIRD_GEAR;

/**
 * 到访申请
 */
public class VisitApplyActivity extends AppCompatActivity implements OnDateSetListener {


    private PhotoAdapter photoAdapter;
    private ArrayList<String> selectedPhotos = new ArrayList<>();
    private JSONArray urlArray;
    private String recommendCode;
    private String accessCode;
    private String timeString;
    private String type;
    private String typetime;
    private String progresstext;
    private ProgressDialog progressDialog;
    private long SelectTime;
    private TimePickerDialog mDialogMonthDayHourMinute;

    private ActivityVisitApplyBinding binding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_visit_apply);

        binding.idBack.setOnClickListener(this::onClick);
        binding.idVisitTime.setOnClickListener(this::onClick);
        binding.idCommit.setOnClickListener(this::onClick);

        EventBus.getDefault().register(this);
        if (getIntent().hasExtra("recommendCode"))
            recommendCode = getIntent().getStringExtra("recommendCode");
        if (getIntent().hasExtra("accessCode"))
            accessCode = getIntent().getStringExtra("accessCode");

        initViews();
        initEvents();
    }


    protected void initViews() {

        binding.idCName.setText(getIntent().getStringExtra("customerName"));
        binding.idCustomerPhone.setText(getIntent().getStringExtra("customerTel"));
        binding.idProjectName.setText(getIntent().getStringExtra("houseName"));

        binding.idPhotosList.setHasFixedSize(true);
        binding.idPhotosList.setLayoutManager(new WrapContentLinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        photoAdapter = new PhotoAdapter(this, selectedPhotos);
        binding.idPhotosList.setAdapter(photoAdapter);
        if (getIntent().hasExtra("type") && !TextUtils.isEmpty(getIntent().getStringExtra("type"))) {
            type = getIntent().getStringExtra("type");
        }
        if (type.equals("0")) {
            binding.endTime.setText("到访时间");
            binding.titleText.setText("到访申请单");
            typetime = "到访时间";
            progresstext = "上传中...";
            binding.idVisitImg.setVisibility(View.VISIBLE);
        } else if (type.equals("1")) {
            binding.endTime.setText("复访时间");
            binding.titleText.setText("复访申请单");
            typetime = "复访时间";
            progresstext = "提交中...";
            binding.viewLine.setVisibility(View.GONE);
            binding.idVisitImg.setVisibility(View.GONE);
        }
        progressDialog = new ProgressDialog(VisitApplyActivity.this, progresstext);
    }

    protected void initData() {
        ///storage/emulated/0/DCIM/banner.png  /storage/emulated/0/DCIM/jpush_notification_iconication_icon.png
    }

    protected void initEvents() {
        photoAdapter.setOnSelectClickLitener(() -> MultiImageSelector.create(VisitApplyActivity.this)
                .showCamera(false)
                .count(10)
                .multi()
                .start(VisitApplyActivity.this, 666));
        photoAdapter.setOnDelClickLitener(p -> {
            if (selectedPhotos.size() >= p) {
                selectedPhotos.remove(p);
                photoAdapter.notifyItemRemoved(p);
                photoAdapter.notifyItemRangeChanged(p, selectedPhotos.size() - p);
            }
        });
        photoAdapter.setOnItemClickLitener(new PhotoAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(int i) {
                Intent intent = new Intent(VisitApplyActivity.this, ImageViewPagerActivity.class);
                intent.putStringArrayListExtra("imgs", selectedPhotos);
                intent.putExtra("position", i + 1);
                startActivity(intent);
            }
        });
        binding.idNotes.addTextChangedListener(new TextWatcher() {
            private CharSequence temp;
            private int SelectionStart;
            private int SelectionEnd;

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                temp = charSequence;
            }

            @Override
            public void afterTextChanged(Editable editable) {
                int number = 200 - editable.length();
                binding.textCount.setText(number + "/200");
                SelectionStart = binding.idNotes.getSelectionStart();
                SelectionEnd = binding.idNotes.getSelectionEnd();
                if (temp.length() > 200) {
                    editable.delete(SelectionStart - 1, SelectionEnd);
                    int tempSelection = SelectionEnd;
                    binding.idNotes.setText(editable);
                    binding.idNotes.setSelection(tempSelection);//设置光标在最后
                }
            }
        });
    }


    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.id_back:
                //返回bre
                finish();
                break;
            case R.id.id_visit_time:
                //预计到访时间
                mDialogMonthDayHourMinute = new TimePickerDialog.Builder()
                        .setType(Type.ALL)
                        .setTitleStringId(typetime)
                        .setCurrentMillseconds(System.currentTimeMillis())
                        .setThemeColor(getResources().getColor(R.color.yellow))
                        .setWheelItemTextNormalColor(getResources().getColor(R.color.textColor_555))
                        .setWheelItemTextSelectorColor(getResources().getColor(R.color.black))
                        .setCallBack(this)
                        .build();
                mDialogMonthDayHourMinute.show(getSupportFragmentManager(), "all");
                break;
            case R.id.id_commit:
                if (type.equals("0")) {
                    //带访提交、
                    if (TextUtils.isEmpty(timeString)) {
                        CustomToast.showToast(this, "请选择到访时间", 1500);
                    } else if (!compareDate(SelectTime)) {
                        CustomToast.showToast(this, "带访时间不能大于当前时间", 1500);
                    } else if (TextUtils.isEmpty(binding.idNameInput.getText().toString())) {
                        CustomToast.showToast(this, "请输入案场销售", 1500);
                    } else if (selectedPhotos.size() == 0) {
                        CustomToast.showToast(this, "请添加图片", 1500);
                    } else {
                        progressDialog.show();
                        urlArray = new JSONArray();
                        ArrayList<File> list = new ArrayList<>();
                        for (int i = 0, j = selectedPhotos.size(); i < j; i++) {
                            File file = new File(selectedPhotos.get(i));
                            list.add(file);
                        }
                        compressWithRx(list);
                    }
                } else if (type.equals("1")) {
                    //复访提交、
                    if (TextUtils.isEmpty(timeString)) {
                        CustomToast.showToast(this, "请选择复访时间", 1500);
                    } else if (!compareDate(SelectTime)) {
                        CustomToast.showToast(this, "复访时间不能大于当前时间", 1500);
                    } else if (TextUtils.isEmpty(binding.idNameInput.getText().toString())) {
                        CustomToast.showToast(this, "请输入案场销售", 1500);
                    } else {
                        reSubmit();
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        binding.idVisitTimeTxt.setText(DateUtil.getTime(millseconds));
        timeString = String.valueOf(millseconds);
        SelectTime = millseconds;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == 666) {

            List<String> photos = null;
            if (data != null) {
                photos = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
            }
            selectedPhotos.clear();

            if (photos != null) {

                selectedPhotos.addAll(photos);
            }
            photoAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 压缩单张图片并上传 RxJava 方式
     */
    private void compressWithRx(ArrayList<File> list) {

        Luban.get(this)
                .load(list)
                .putGear(THIRD_GEAR)
                .asObservable()
                .flatMap(new Func1<File, Observable<String>>() {
                    @Override
                    public Observable<String> call(File file) {
                        Map<String, String> header = new HashMap<>();
                        header.put("token", ACache.get(VisitApplyActivity.this).getAsString("token") == null ? "" : ACache.get(VisitApplyActivity.this).getAsString("token"));
                        header.put("cookie", null == DbUtil.getDB(VisitApplyActivity.this).single().queryById(200, SaveCookieBean.class) ? "" : DbUtil.getDB(VisitApplyActivity.this).single().queryById(200, SaveCookieBean.class).getCookie());

                        return RxUpLoad.get(VisitApplyActivity.this)
                                .url(ApiConfig.IMG_UPLOAD)
                                .fileName(System.currentTimeMillis() + ".jpg")
                                .file(file)
                                .key("uploadFile")
                                .header(header)
                                .asObservable();
                    }
                })

                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {

                        JSONObject jsonObject = JSON.parseObject(s);
                        if (jsonObject.getString("code").equals("200")) {
                            JSONObject o = new JSONObject();
                            String url = jsonObject.getString("data") == null ? "" : jsonObject.getString("data");
                            o.put("url", url);
                            o.put("name", System.currentTimeMillis() + ".jpg");
                            urlArray.add(o);
                        }

                        if (urlArray.size() == selectedPhotos.size()) {
                            submit();
                        }
                    }
                });
    }


    private void submit() {
        JSONObject jsonObject = new JSONObject();
        JSONObject j = new JSONObject();
        j.put("recommendCode", recommendCode);
        j.put("accessTime_String", DateUtil.getTime(timeString, "yyyy-MM-dd HH:mm:ss"));
        j.put("caseName", binding.idNameInput.getText().toString());
        j.put("remark", binding.idNotes.getText().toString());
        jsonObject.put("agentAccess", j.toString());
        jsonObject.put("imglist", urlArray.toString());

        OkHttpUtils.postString()
                .url(ApiConfig.NEW_SAVE_VISIT)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        call.cancel();
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing())
                            progressDialog.dismiss();
                        if (DataFilter.filter(VisitApplyActivity.this, response)) {
                            CustomToast.showToast(VisitApplyActivity.this, "提交成功", 1500);
                            finish();
                        }
                    }
                });
    }


    /**
     * 复访提交
     */
    private void reSubmit() {
        progressDialog.show();
        JSONObject object = new JSONObject();
        JSONObject j = new JSONObject();
        j.put("accessCode", accessCode);
        j.put("repeatTime_Str", DateUtil.getTime(timeString, "yyyy-MM-dd HH:mm:ss"));
        j.put("caseName", binding.idNameInput.getText().toString());
        j.put("remark", binding.idNotes.getText().toString());
        object.put("agentRepeatAccess", j.toString());

        OkHttpUtils.postString()
                .url(ApiConfig.SAVE_RE_VISIT)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(object.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        call.cancel();
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(VisitApplyActivity.this, response)) {
                            if (null != progressDialog && progressDialog.isShowing())
                                progressDialog.dismiss();
                            CustomToast.showToast(VisitApplyActivity.this, "提交成功", 1500);
                            finish();
                        }
                    }
                });
    }

    /**
     * 比较日期
     */
    public boolean compareDate(long time) {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date currentTime = new Date(System.currentTimeMillis());//currentTime就是系统当前时间
        synchronized (fmt) {
            String currentSignTime = fmt.format(currentTime);
            if (!TextUtils.isEmpty(currentSignTime)) {
                try {
                    if (fmt.parse(currentSignTime).getTime() > time) {  // 复访/带访时间小于当前时间
                        return true;
                    } else {
                        return false;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        super.onDestroy();
    }
}
